# -*- coding: utf-8 -*-

#===============================================================================
# GettingTasksDone.com project Models declarations file
# 2007-10-26: Sergeyev V.V.
#===============================================================================

from django.db import models
from django.db.models import OneToOneField
from django.db.models.fields.related import SingleRelatedObjectDescriptor 

from django.contrib.auth.models import User

import datetime
import time

#------------------------------------------------------------------------------ 
#Вспомогательные классы для добавления к стандартной модели User поля Account.
#Увы, наследовать модели в Джанго нельзя.
#------------------------------------------------------------------------------
class AutoSingleRelatedObjectDescriptor(SingleRelatedObjectDescriptor): # this line just can't be too long, right?
    def __get__(self, instance, instance_type=None):
        try:
            return super(AutoSingleRelatedObjectDescriptor, self).__get__(instance, instance_type)
        except self.related.model.DoesNotExist:
            obj = self.related.model(**{self.related.field.name: instance})
            obj.show_customers = True
            obj.show_projects = True
            obj.show_tasks = True
            obj.tasks_shared = False
            obj.share_users = ""
            obj.save()
            return obj

#------------------------------------------------------------------------------
class AutoOneToOneField(OneToOneField):
    '''
    OneToOneField, которое создает зависимый объект при первом обращении
    из родительского, если он еще не создан.
    '''
    def contribute_to_related_class(self, cls, related):
        setattr(cls, related.get_accessor_name(), AutoSingleRelatedObjectDescriptor(related))
        if not cls._meta.one_to_one_field:
            cls._meta.one_to_one_field = self

#------------------------------------------------------------------------------ 
class Profile(models.Model):
    """
    User's profile
    """
    user = AutoOneToOneField(User, related_name="profile", editable=False)
    
    show_customers = models.BooleanField()
    show_projects = models.BooleanField()
    show_tasks = models.BooleanField()
    openid = models.CharField(maxlength="200", blank=True)
    tasks_shared = models.BooleanField()
    share_users = models.TextField()

    def __str__(self):
        return self.user.username
    
    def __unicode__(self):
        return self.user.username

    class Meta:
        verbose_name = "User's profile"
        verbose_name_plural = "User's profiles"
        
    class Admin:
        list_display = ('user', 'tasks_shared', 'show_customers', 'show_projects', 'show_tasks')

#------------------------------------------------------------------------------
# Managers to work with "objects" and "deleted_objects"
# we add custom deleting via field "deleted" in Model
#------------------------------------------------------------------------------ 
class AllCustomManager(models.Manager):
    def get_query_set(self):
        return super(AllCustomManager, self).get_query_set()
    
#------------------------------------------------------------------------------ 
class CustomManager(models.Manager):
    def get_query_set(self):
        return super(CustomManager, self).get_query_set().filter(deleted__exact=False)

#------------------------------------------------------------------------------ 
class DeletedCustomManager(models.Manager):
    def get_query_set(self):
        return super(DeletedCustomManager, self).get_query_set().filter(deleted__exact=True)

#------------------------------------------------------------------------------ 
# Customer model
#------------------------------------------------------------------------------ 
class Customer(models.Model):
    """
    Project customer
    """
    user = models.ForeignKey(User, editable=False)
    name = models.CharField("Name", maxlength="200")
    email = models.EmailField("E-mail", blank=True)
    text = models.TextField("Description", blank=True)
    
    deleted = models.BooleanField(editable=False)

#    objects = CustomManager()
#    deleted_objects = DeletedCustomManager()
#    all_objects = AllCustomManager()

    def __str__(self):
        return self.name
    
    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = "Project customer"
        verbose_name_plural = "Project customers"
        
    class Admin:
        list_display = ('user', 'name', 'email')

#------------------------------------------------------------------------------ 
# Project model
#------------------------------------------------------------------------------
class Project(models.Model):
    """
    Project
    """
    user = models.ForeignKey(User, editable=False)
    name = models.CharField("Name", maxlength="200")
    customer = models.ForeignKey(Customer, blank=True, null=True)
    hour_rate = models.FloatField("Hour rate", max_digits=5, decimal_places=2, blank=True)
    text = models.TextField("Description", blank=True)
    
    deleted = models.BooleanField(editable=False)

#    objects = CustomManager()
#    deleted_objects = DeletedCustomManager()
#    all_objects = AllCustomManager()

    def __str__(self):
        return self.name
    
    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = "Project"
        verbose_name_plural = "Projects"
        ordering = ['name']
        
    class Admin:
        list_display = ('user', 'name', 'customer')

#------------------------------------------------------------------------------ 
# Task model
#------------------------------------------------------------------------------ 
class Task(models.Model):
    """
    Task. The smallest thing you can split Project.
    """
    user = models.ForeignKey(User, editable=False)
    name = models.CharField("Summary", maxlength="200")

    project = models.ForeignKey(Project, blank=True, null=True)
    #customer = models.ForeignKey(Customer, blank=True, null=True)
    
    task_date = models.DateField("Date", blank=True, null=True)
    time_spent = models.FloatField("Hours spent", max_digits=5, decimal_places=2)
    text = models.TextField("Description", blank=True)
    done = models.BooleanField("Done")

    deleted = models.BooleanField(editable=False)

#    objects = CustomManager()
#    deleted_objects = DeletedCustomManager()
      
    def __str__(self):
        return self.name
    
    def __unicode__(self):
        return self.name
    
    class Meta:
        verbose_name = "Task or idea"
        verbose_name_plural = "Tasks & ideas"
        
    class Admin:
        list_display = ('user', 'name', 'deleted')

#------------------------------------------------------------------------------ 
class HotTask(models.Model):
    """
    Приближается Рождество. Вы можете помочь другим людям не забыть сделать важные дела :)
     - купить подарки семье и друзьям
     - выбрать подарок маме
     - выбрать красивый подарок жене
     - отправить письмо с поздравлениями лучшему другу
     - найти красивые рождественские открытки и отправить их друзьям детства
    """
    user = models.ForeignKey(User, editable=False)
    name = models.CharField("Summary", maxlength="200")
    saved_count = models.IntegerField("How many people added it to their tasks", editable=False)
    deleted = models.BooleanField(editable=False)

    def __str__(self):
        return self.name
    
    def __unicode__(self):
        return self.name
    
    class Meta:
        verbose_name = "Hot task"
        verbose_name_plural = "Hot tasks"
        
    class Admin:
        list_display = ('user', 'name', 'saved_count', 'deleted')

#------------------------------------------------------------------------------ 
class Ticket(models.Model):
    username = models.CharField("User name", maxlength="100")
    comment = models.TextField()

    def __str__(self):
        return "Ticket #%i" % self.id
    
    def __unicode__(self):
        return "Ticket #%i" % self.id
    
    class Admin:
        pass

#------------------------------------------------------------------------------ 
class Language(models.Model):
    name = models.CharField(maxlength="100")
    language_code = models.CharField(maxlength="20")
    
    def __str__(self):
        return self.name
    
    def __unicode__(self):
        return self.name
    
    class Admin:
        list_display = ('name', 'language_code')

#------------------------------------------------------------------------------ 
class Motivation(models.Model):
    text = models.CharField(maxlength="200")
    author = models.CharField(maxlength="100", blank=True)
    author_url = models.CharField(maxlength="100", blank=True)
    language = models.ForeignKey(Language)
    
    def __str__(self):
        return self.text
    
    def __unicode__(self):
        return self.text
    
    class Admin:
        fields = (
            (None, {
                'classes': 'wide',
                'fields': ('text', 'author', 'author_url', 'language')
                }),
            )
        list_display = ('author', 'language', 'text')

#------------------------------------------------------------------------------ 
class Adds(models.Model):
    customer = models.CharField(maxlength="100")
    code = models.TextField()
    
    def __str__(self):
        return "Add #%s" % self.id

    def __unicode__(self):
        return "Add #%s" % self.id

    class Admin:
        pass

#------------------------------------------------------------------------------ 

